<script setup>
import { ref, nextTick, onMounted } from 'vue'
import { Promotion } from '@element-plus/icons-vue'
import { marked } from 'marked'
import config from '@/config/config'

// 当前输入的消息
const message = ref('')

// 聊天记录列表：{ type: 'req' | 'res', text: string, html?: string, loading?: boolean }
const chatList = ref([])

// 智能推荐 follow_up 列表
const recommendations = ref([])

// 获取 textarea 和滚动容器的引用
const textareaRef = ref(null)
const scrollbarRef = ref(null)

// 自动调整高度
const autoResize = () => {
  const el = textareaRef.value
  if (!el) return
  el.style.height = 'auto'
  const maxHeight = 150
  const newHeight = Math.min(el.scrollHeight, maxHeight)
  el.style.height = `${newHeight}px`
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    const scrollEl = scrollbarRef.value?.wrap
    if (scrollEl) scrollEl.scrollTop = scrollEl.scrollHeight
  })
}

// 发送消息
const sendMessage = async (textParam) => {
  const text = (textParam ?? message.value)?.trim()
  if (!text) return

  // 添加用户消息
  chatList.value.push({ type: 'req', text })

  // 清空输入框
  message.value = ''
  nextTick(() => {
    autoResize()
    textareaRef.value?.focus()
  })

  // 清空上一次推荐
  recommendations.value = []

  // 占位 AI 回复（loading = true）
  const aiMsg = { type: 'res', text: '', html: '', loading: true }
  chatList.value.push(aiMsg)
  scrollToBottom()

  try {

    const response = await fetch(config.api_send_message_url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        // "accessToken": config.accessToken
      },
      body: JSON.stringify({
        sessionId: config.sessionId_assistant,
        role: "user",
        content: text,
        timestamp: new Date().toISOString().slice(0, 19).replace('T', ' '),
        userId: 1
      }),
    })

    const reader = response.body?.getReader()
    const decoder = new TextDecoder()
    let buffer = ""

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      buffer += decoder.decode(value, { stream: true })
      const parts = buffer.split("\n\n")
      buffer = parts.pop()

      for (const line of parts) {
        if (line.startsWith("data:")) {
          try {
            const data = JSON.parse(line.slice(5).trim())
            if (!data.content) continue

            if (data.type === 'answer') {
              aiMsg.loading = false
              const fullText = data.content
              let index = 0
              const interval = setInterval(() => {
                if (index >= fullText.length) {
                  clearInterval(interval)
                  return
                }
                aiMsg.text += fullText[index]
                aiMsg.html = marked.parse(aiMsg.text)
                chatList.value = [...chatList.value]
                scrollToBottom()
                index++
              }, 30)
            } else if (data.type === 'follow_up') {
              recommendations.value.push(data.content)
            }
          } catch (err) {
            console.error("解析失败:", line, err)
          }
        }
      }
    }
  } catch (err) {
    aiMsg.loading = false
    aiMsg.text = "❌ 出错了，请稍后再试"
    aiMsg.html = aiMsg.text
    chatList.value = [...chatList.value]
    console.error(err)
  }
}

// 点击智能推荐发送消息
const handleRecommendationClick = (text) => {
  sendMessage(text)
}

// 绑定回车发送
const handleKeydown = (e) => {
  if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.altKey) {
    e.preventDefault()
    sendMessage()
  }
}

// 开启新对话
const startNewChat = () => {
  chatList.value = []
  recommendations.value = []
  message.value = ''
  textareaRef.value?.focus()
}

// 控制小机器人的消失
const isHidden = ref(false)

// 页面加载后自动聚焦输入框
onMounted(() => {
  textareaRef.value?.focus()
})
</script>

<template>
  <el-scrollbar ref="scrollbarRef" height="60vh">
    <h2 style="color: #1475fb">我是AI助教</h2>
    <p style="color: rgba(0, 0, 0, 0.5); font-size: 14px; padding: 10px 0">
      我可以帮你解答学习疑惑，也会提供陪伴和支持😊
    </p>

    <div class="recommend-box">
      <div>
        <div style="font-size: 14px; font-weight: 600">资源推荐</div>
        <div style="font-size: 12px; color: rgba(0, 0, 0, 0.5)">海量优质资源，一键送达</div>
      </div>
      <div class="recommend-img"></div>
    </div>

    <!-- 聊天消息列表 -->
    <div
        v-for="(item, index) in chatList"
        :key="index"
        :class="['message-box', item.type === 'req' ? 'req-box' : 'res-box']"
    >
      <div v-if="item.type === 'res'" class="ai-avatar"></div>
      <div v-if="item.type === 'req'" class="req">{{ item.text }}</div>
      <div v-else class="res">
        <span v-if="item.loading" class="loading-dots">正在输入<span>.</span><span>.</span><span>.</span></span>
        <span v-else v-html="item.html"></span>
      </div>
      <div v-if="item.type === 'req'" class="user-avatar"></div>
    </div>

    <!-- 智能推荐显示 -->
    <div v-if="recommendations.length" class="follow-up-box">
      <div style="font-size: 12px; color: #999; margin-bottom: 5px;">智能提示：</div>
      <div
          v-for="(item, index) in recommendations"
          :key="index"
          class="follow-up-item"
          @click="handleRecommendationClick(item)"
      >
        {{ item }}
      </div>
    </div>
  </el-scrollbar>

  <div class="input-box">
    <div class="open-new-box" @click="startNewChat">
      <img id="img1" src="@/assets/images/AI/assistant/新建对话.png" alt="" width="20px" height="20px" />
      <img id="img2" src="@/assets/images/AI/assistant/新建对话-触发.png" alt="" width="0" height="0" />
      开启新对话
    </div>

    <textarea
        ref="textareaRef"
        v-model="message"
        placeholder="请输入您的问题"
        @input="autoResize"
        @keydown="handleKeydown"
    ></textarea>

    <div style="display: flex; justify-content: right; align-items: center">
      <span style="color: rgba(0, 0, 0, 0.3);font-size: 12px">shift+enter换行，enter发送</span>
      <el-button type="primary" round style="margin-left: 10px" @click="sendMessage(message.value)">
        <el-icon><Promotion /></el-icon>发送
      </el-button>
    </div>

    <div :class="['robot-box', { 'hidden': isHidden }]" @click="isHidden = true"></div>
  </div>
</template>

<style scoped>
.ai-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-image: url('@/assets/images/AI/assistant/AI头像.png');
  background-position: center center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 20px;
  margin-left: 15px;
  background-image: url('@/assets/images/AI/assistant/用户头像.png');
  background-position: center center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.message-box {
  display: flex;
  margin: 10px 0;
}
.message-box.req-box {
  justify-content: flex-end;
}
.message-box.res-box {
  justify-content: flex-start;
}
.req,
.res {
  max-width: 80%;
  min-height: 40px;
  padding: 12px 16px;
  border-radius: 12px;
  line-height: 1.5;
  font-size: 14px;
  word-wrap: break-word;
}
.req {
  background-color: #1475fb;
  color: white;
  border-bottom-right-radius: 4px;
}
.res {
  color: #333;
  border-bottom-left-radius: 4px;
}
.loading-dots span {
  display: inline-block;
  animation: blink 1s infinite;
}
.loading-dots span:nth-child(2) {
  animation-delay: 0.2s;
}
.loading-dots span:nth-child(3) {
  animation-delay: 0.4s;
}
@keyframes blink {
  0%, 20%, 50%, 80%, 100% { opacity: 1; }
  10%, 30%, 60%, 90% { opacity: 0; }
}
.follow-up-box {
  margin: 10px 0;
  padding: 8px 12px;
  background: #f5f7fa;
  border-radius: 8px;
}
.follow-up-item {
  font-size: 13px;
  color: #555;
  padding: 4px 0;
  cursor: pointer;
}
.follow-up-item:hover {
  color: #1475fb;
}
.recommend-box {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
  align-items: center;
  height: 50px;
  width: 500px;
  background-color: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  margin: 15px 0;
}
.recommend-box:hover {
  box-shadow: 0 0 20px 8px #e1eeff;
}
.recommend-img {
  margin-right: 10px;
  width: 58px;
  height: 40px;
  background-image: url('@/assets/images/AI/assistant/资源推荐.png');
  background-position: center center;
  background-size: 100% 100%;
  background-repeat: no-repeat;
}
.open-new-box {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  top: -40px;
  padding: 3px 10px;
  width: 110px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  font-size: 12px;
  border-radius: 12px;
  color: #6da7f2;
  cursor: pointer;
  transition: all 0.3s ease;
}
.open-new-box:hover {
  background-color: #4fa1fb;
  color: white;
}
.open-new-box:hover #img1 {
  display: none;
}
.open-new-box:hover #img2 {
  width: 20px;
  height: 20px;
}
.input-box {
  position: absolute;
  bottom: -120px;
  width: 100%;
  padding: 10px;
  border-radius: 10px;
  border: 2px solid #aed0fc;
  background-color: white;
  margin-top: 6px;
}
.input-box textarea {
  width: 100%;
  min-height: 50px;
  max-height: 150px;
  padding: 10px;
  font-size: 14px;
  color: #333;
  border: none;
  outline: none;
  resize: none;
  box-sizing: border-box;
  overflow-y: auto;
  background-color: transparent;
  line-height: 1.5;
}
.robot-box {
  width: 140px;
  height: 170px;
  position: absolute;
  bottom: 18px;
  right: -90px;
  background-image: url('@/assets/images/home/AI助手.png');
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: 1000;
  cursor: pointer;
  transition: all 0.3s ease;
}
.hidden {
  width: 0;
  height: 0;
}
</style>
